<template>
  <div id="chat" class="page">
    <div class="content">
      <h1>当前人数：{{ total }}</h1>
      <div ref="wrapper" class="message">
        <div class="clear" v-for="(item, i) in messageList" :key="i">
          <div
            :class="{
              'message-item': true,
              client: item.origin === 'client'
            }"
            v-if="item.origin != 'server' || item.username != username"
          >
            <div>
              <div>用户：{{ item.username }} --- {{ item.origin }}</div>
              <div>{{ item.message }}</div>
            </div>
          </div>
        </div>
      </div>
      <div>
        <el-input
          v-model="value"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          placeholder="Please input"
        />
      </div>
    </div>
    <el-row>
      <el-button @click="send">发送</el-button>
      <el-button @click="closeConnect">下线</el-button>
      <el-button @click="initConnect">重新连接</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
import { computed, nextTick, onMounted, ref } from '@vue/runtime-core'

import { getConn } from '@/utils/websocket'
import store from '@/store'
import { ElMessage } from 'element-plus'

export default {
  setup () {
    const total = ref('')
    const wrapper = ref(null)
    const value = ref('')
    var socket = null

    const messageList = ref([])
    const username = computed(() => store.getters.name)
    function initConnect () {
      if (!socket || socket.readyState !== 1) {
        socket = getConn('ws://127.0.0.1:8000/ws')
        socket.onmessage = onMessage
      }
    }
    function closeConnect () {
      if (socket && socket.readyState === 1) {
        socket.close()
      } else {
        ElMessage({
          message: '连接已关闭',
        })
      }
    }

    function send () {
      if (socket && socket.readyState === 1) {
        console.log('send value', socket, JSON.stringify({ test: 'hehehe' }))
        socket.send(JSON.stringify(value.value))

        insertEl({
          username: username.value,
          message: value.value,
          origin: 'client',
        })
        value.value = ''
      } else {
        ElMessage({
          message: '连接已关闭',
        })
      }
    }
    function onMessage (e) {
      let data
      try {
        data = JSON.parse(e.data)
      } catch (error) {
        console.log(error)
        return
      }
      data.origin = 'server'
      console.log('serve message', data)
      if (data.action === 'total') {
        total.value = data.message
      } else {
        insertEl(data)
      }
    }
    function insertEl (data) {
      messageList.value.push(data)
      nextTick(() => {
        console.log('h', wrapper.value.scrollHeight)
        wrapper.value.scrollTo(0, wrapper.value.scrollHeight)
      })
    }
    onMounted(() => {
      initConnect()
    })
    console.log('username', username.value)
    return {
      value,
      send,
      messageList,
      username,
      wrapper,
      initConnect,
      total,
      closeConnect,
    }
  },
}
</script>

<style lang="less">
.message {
  border: 1px solid red;
  width: 100%;
  height: 300px;
  overflow: auto;
  margin: 20px 0;
  .message-item {
    padding: 4px 15px;
    border: 1px solid skyblue;
    margin: 6px;
    width: fit-content;
    border-radius: 8px;
    &.client {
      background: #15d37f;
      float: right;
    }
  }
}
.clear::after {
  content: "";
  clear: both;
  display: block;
}
</style>
